package com.mbt.deal.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.alibaba.android.arouter.launcher.ARouter;
import com.mbt.deal.R;
import com.mbt.deal.R2;
import com.mbt.deal.api.RxBus;
import com.mbt.deal.bean.CoinListBean;
import com.mbt.deal.bean.MessageBean;
import com.mbt.deal.ui.contract.OrderSaleContract;
import com.mbt.deal.ui.fragment.DealbuinessFragment2;
import com.mbt.deal.ui.model.OrderSaleBuyModel;
import com.mbt.deal.ui.presenter.OrderBuySalePresenter;
import com.mbt.deal.ui.widgets.BottomLineTextView;
import com.mbt.deal.ui.widgets.CashierInputFilter;
import com.mbt.deal.ui.widgets.LoadDialog;
import com.mbt.deal.ui.widgets.MoneyKindPop;
import com.mbt.deal.util.Arith;
import com.mbt.deal.util.ImageLoadUtil;
import com.mbt.deal.util.LogUtils;
import com.mbt.deal.util.NToast;
import com.mbt.deal.util.SealConst;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 创建日期：2018/8/16 on 14:05
 * 描述:
 * 作者:王甜
 */
public class OrderSaleorBuyActivity extends BaseActivity<OrderBuySalePresenter, OrderSaleBuyModel> implements OrderSaleContract.View {

    @BindView(R2.id.ll_back)
    LinearLayout llBack;
    @BindView(R2.id.txt_title)
    TextView txtTitle;
    @BindView(R2.id.ll_title)
    LinearLayout llTitle;
    @BindView(R2.id.txt_recharge)
    TextView txtRecharge;
    @BindView(R2.id.iv_headportrait)
    ImageView ivHeadportrait;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_des)
    TextView tvDes;
    @BindView(R2.id.cash_money)
    TextView cashMoney;
    @BindView(R2.id.tv_coin_name)
    TextView tv_coin_name;
    @BindView(R2.id.apay_money)
    TextView apayMoney;
    @BindView(R2.id.view_flipper)
    ViewFlipper viewFlipper;
    @BindView(R2.id.txt_cur_money_desc)
    TextView txtCurMoneyDesc;
    @BindView(R2.id.txt_cur_money)
    TextView txtCurMoney;
    @BindView(R2.id.txt_sale_money_desc)
    TextView txtSaleMoneyDesc;
    @BindView(R2.id.txt_sale_money)
    EditText etSaleMoney;
    @BindView(R2.id.txt_sale_count_desc)
    TextView txtSaleCountDesc;
    @BindView(R2.id.txt_sale_count)
    EditText txtSaleCount;
    @BindView(R2.id.txt_buy_total_money_desc)
    TextView txtBuyTotalMoneyDesc;
    @BindView(R2.id.txt_buy_total_money)
    TextView txtBuyTotalMoney;
    @BindView(R2.id.sure)
    Button sure;

    int orderType = 1;//购买2出售

    private SharedPreferences sp;

    String userDesc;//用户描述

    String nowPrice;//当前价格

    double nowPriceDou;//当前价格

    String coinCount;//币种个数

    private String coinName;//币种

    private String coinId;//币id

    private String cashmoney;

    int percentInt = 0;
    private int saleCount = 0;
    List<MessageBean> messageBeanList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sale_buy_order);
        ButterKnife.bind(this);

        mPresenter.setVM(this, mModel);
        sp = act.getSharedPreferences("config", MODE_PRIVATE);

        initData();
    }

    private void initData() {
        InputFilter[] filters = {new CashierInputFilter()};
        etSaleMoney.setFilters(filters);
        String coinName = getIntent().getStringExtra("coinName");

        String phone = sp.getString(SealConst.SEALTALK_LOGING_PHONE, "");
        String heardPhotoUrl = sp.getString(SealConst.SEALTALK_LOGING_PORTRAIT, "");
        String niceName = sp.getString(SealConst.SEALTALK_LOGIN_NAME, "");
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            orderType = bundle.getInt("orderType");
            userDesc = bundle.getString("userDesc");
            nowPrice = bundle.getString("nowPrice");
            coinCount = bundle.getString("coinCount");
            coinName = bundle.getString("coinName");
            coinId = bundle.getString("coinId");
            cashmoney = bundle.getString("cashmoney");
            cashMoney.setText(cashmoney);
            messageBeanList = (List<MessageBean>) bundle.getSerializable("messageBeanList");
            try {
                nowPriceDou = Double.parseDouble(nowPrice);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (orderType == 1) {
            //购买订单
            txtSaleMoneyDesc.setText("购买价格：");
            txtSaleCountDesc.setText("购买数量：");
            txtBuyTotalMoneyDesc.setText("购买总额：");
            txtSaleCount.setHint("请输入购买数量");
            sure.setText("预约购买");
            txtTitle.setText("发布"+coinName+"购买订单");
        } else {
            //出售订单
            txtSaleMoneyDesc.setText("出售价格：");
            txtSaleCountDesc.setText("出售数量：");
            txtBuyTotalMoneyDesc.setText("出售总额：");
            sure.setText("预约出售");
            txtSaleCount.setHint("请输入出售数量");
            txtTitle.setText("发布"+coinName+"出售订单");
        }

        ImageLoadUtil.loadImage(heardPhotoUrl, ivHeadportrait);
        if (TextUtils.isEmpty(niceName)) {
            tvName.setText("无");
        } else {
            tvName.setText(niceName);
        }
        tvDes.setText(userDesc);
        tv_coin_name.setText(coinName);
        apayMoney.setText(coinCount);
        txtCurMoney.setText(nowPrice);
        etSaleMoney.setText(nowPrice);

        viewFlipper.removeAllViews();
        if (messageBeanList != null) {
            for (int i = 0; i < messageBeanList.size(); i++) {
                TextView textView = new TextView(act);
                textView.setTextColor(Color.parseColor("#ffffff"));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15f);
                textView.setSingleLine(true);
                textView.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
                textView.setText(messageBeanList.get(i).getTitle());
                viewFlipper.addView(textView);
            }
        }


        viewFlipper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(act, MessageActivity.class);
                startActivity(intent);
            }
        });

        txtSaleCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                saleCount = Integer.parseInt(s.trim());
                if (TextUtils.isEmpty(etSaleMoney.getText().toString())) {
                    return;
                }
                txtBuyTotalMoney.setText(multip(nowPriceDou, saleCount) + "");
            }
        });
        etSaleMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                if (TextUtils.isEmpty(s)) {
                    return;
                }
                nowPriceDou = Double.parseDouble(s);
                if (TextUtils.isEmpty(txtSaleCount.getText().toString())) {
                    return;
                }

                txtBuyTotalMoney.setText(multip(nowPriceDou, saleCount) + "");
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @OnClick({R2.id.ll_back, R2.id.ll_title, R2.id.txt_recharge, R2.id.sure})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.ll_back) {
            finish();
        } else if (i == R.id.ll_title) {

        } else if (i == R.id.txt_recharge) {
            ARouter.getInstance().build("/personal/RechargeActivity")
                    .navigation();
        } else if (i == R.id.sure) {
            if (TextUtils.isEmpty(txtSaleCount.getText().toString())) {
                if (orderType == 1) {
                    NToast.shortToast(act, "请输入购买数量");
                } else {
                    NToast.shortToast(act, "请输入出售数量");
                }
                return;
            }
            if (TextUtils.isEmpty(etSaleMoney.getText().toString())) {
                if (orderType == 1) {
                    NToast.shortToast(act, "请输入购买价格");
                } else {
                    NToast.shortToast(act, "请输入出售价格");
                }
                return;
            }
            LoadDialog.show(act);
            if (orderType == 1) {
                //购买
                mPresenter.buy(coinId + "", txtSaleCount.getText().toString(), etSaleMoney.getText().toString());
            } else {
                mPresenter.sale(coinId + "", txtSaleCount.getText().toString(), etSaleMoney.getText().toString());
            }
        }
    }

    @Override
    public void sale(String jsonValues) {
        LoadDialog.dismiss(act);
        NToast.shortToast(act, "发布成功");
        RxBus.getInstance().post(DealbuinessFragment2.DEALBUINESSFRAGMENTRXBUS, "");
        finish();
    }

    @Override
    public void buy(String jsonValues) {
        LoadDialog.dismiss(act);
        NToast.shortToast(act, "发布成功");
        RxBus.getInstance().post(DealbuinessFragment2.DEALBUINESSFRAGMENTRXBUS, "");
        finish();
    }

    @Override
    public void onError(String errorMsg) {
        LoadDialog.dismiss(act);
    }

    private BigDecimal multip(double a, double b) {
        BigDecimal a1 = BigDecimal.valueOf(a);
        BigDecimal b1 = BigDecimal.valueOf(b);
        BigDecimal c = a1.multiply(b1);
        return c;
    }
}
